<template>
  <div class="vc-page vc-page-parts" style="position:relative;overflow:hidden;">
    <!-- 左侧 - 用户组树 -->
    <div class="part-left">
      <div class="tree-title">
        组织机构用户树
        <el-tooltip content="刷新" placement="bottom">
          <i @click="filterText='';getAllRole(id)" class="vc-icon vc-icon-refresh"></i>
        </el-tooltip>
      </div>
      <el-input
        v-if="rgTreeData.length"
        v-model="filterText"
        placeholder="请输入关键字"
        class="vc-search-input"
        size="small"
        clearable>
      </el-input>
      <el-tree
        :current-node-key="curkey"
        :data="rgTreeData"
        :defaultExpandedKeys="expandedKeys"
        :empty-text="treeEmptyText"
        :expand-on-click-node="false"
        :props="defaultProps"
        :render-after-expand="true"
        :filter-node-method="filterNode"
        @node-click="rghandleNodeClick"
        class="org-tree"
        highlight-current
        node-key="id"
        ref="rgTree"
      >
        <span class="slot-tree" slot-scope="{ node }">
          <i
            :class="node.data.type == 'user' ? 'vc-icon-tree-user' : 'vc-icon-tree-org'"
            class="vc-icon"
          ></i>
          <span>{{ node.label }}</span>
        </span>
      </el-tree>
    </div>
    <!-- 右侧 - 详情与表格 -->
    <div class="part-right">
      <!--右侧节点信息-->
      <el-tabs v-model="tabConfig.activeName">
        <el-tab-pane
          :key="idx"
          :label="item.title"
          :name="item.name"
          class="tabTitle"
          v-for="(item,idx) in tabConfig.items"
        >
          <div>
            <!-- 操作按钮 -->
            <div class="vc-btns">
              <el-button
                :class="btn.class?btn.class:''"
                :disabled="btn.disabled?btn.disabled():false"
                :key="idx"
                :type="btn.type?btn.type:''"
                @click="btn.fn"
                size="small"
                v-for="(btn,idx) in item.option"
              >{{btn.title}}</el-button>
            </div>
            <!-- 列表展示 -->
            <div class="vc-table">
              <Tables
                :columns="item.tableConfig.columns"
                :stripe="true"
                @on-selection-change="handleSelectionChange"
                ref="tables"
                v-model="item.tableConfig.tableData"
              />
              <!-- 分页 -->
              <el-pagination
                :current-page.sync="pageConfig.pageNum"
                :page-size="15"
                :total="pageConfig.total"
                @current-change="handleCurrentChange"
                layout="total, prev, pager, next"
                v-if="paginationShow"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 授予角色 -->
    <SelectBox
      ref="selectBox"
      :allNode="addRoleConfig.allNode"
      :boxDialogVisible="addRoleConfig.editVisible"
      :checkedNode="addRoleConfig.checked"
      :defaultProps="optionUgroupConfig.defaultProps"
      :iconConfig="addRoleConfig.iconConfig"
      :listStyle="addRoleConfig.listStyle"
      :rightKey="addRoleConfig.rightKey"
      :searchConfig="addRoleConfig.search"
      :title="addRoleConfig.title"
      @close="closeAddRoleDialog"
      @save="saveAdd"
    />
    <!-- 用户组操作 -->
    <SelectBox
      :allNode="optionUgroupConfig.allNode"
      :boxDialogVisible="optionUgroupConfig.editVisible"
      :checkedNode="optionUgroupConfig.checked"
      :defaultProps="optionUgroupConfig.defaultProps"
      :iconConfig="optionUgroupConfig.iconConfig"
      :indep="true"
      :listStyle="optionUgroupConfig.listStyle"
      :rightKey="optionUgroupConfig.rightKey"
      :searchConfig="optionUgroupConfig.search"
      :title="optionUgroupConfig.title"
      @close="closeOptionUgroupDialog"
      @save="optionUgroupSave"
    />
  </div>
</template>

<script>
import SelectBox from '_c/selectBox'
import supForm from '_c/form'
import Tables from '_c/tables'
export default {
  name: 'userRole',
  components: { Tables, supForm, SelectBox },
  data () {
    return {
      // 分页配置
      pageConfig: {
        pageNum: 1,
        pageSize: 15,
        total: 0
      },
      tabConfig: {
        items: [
          {
            name: 'ugroup',
            title: '用户组',
            tableConfig: {
              columns: [
                {
                  type: 'selection',
                  width: '50'
                },
                {
                  key: 'index',
                  title: '序号',
                  width: '50',
                  type: 'index'
                },
                {
                  key: 'name',
                  title: '用户组名'
                }
              ],
              tableData: []
            },
            option: [
              {
                title: '维护用户组',
                class: 'multi-words',
                type: 'primary',
                fn: () => {
                  this.optionUgroup({
                    data: {
                      ugroupId: this.id
                    }
                  })
                }
              },
              {
                title: '删除',
                type: '',
                disabled: () => {
                  return this.selectedIds.length === 0
                },
                fn: () => {
                  this.$confirmBox(this.deleteUgroup)
                }
              }
            ]
          },
          {
            name: 'role',
            title: '角色',
            tableConfig: {
              columns: [
                {
                  type: 'selection'
                },
                {
                  title: '序号',
                  type: 'index',
                  width: 70
                },
                {
                  title: '角色名称',
                  key: 'name'
                },
                {
                  title: '角色描述',
                  key: 'descr'
                }
              ],
              tableData: []
            },
            option: [
              {
                title: '操作角色',
                class: 'multi-words',
                type: 'primary',
                fn: () => {
                  this.addrole()
                }
              },
              {
                title: '删除',
                type: '',
                disabled: () => {
                  return this.selectedIds.length === 0
                },
                fn: () => {
                  this.$confirmBox(this.deleteRole)
                }
              }
            ]
          }
        ],
        activeName: 'ugroup'
      },
      // 右侧 点击右键
      RightBox: [],
      // 菜单
      menuVisible: false,
      addChildModelFlage: false,
      addPermission: false,
      patchModel: false,
      patchPerModel: false,
      // 组织机构树
      curkey: '',
      treeEmptyText: ' ',
      rgTreeData: [],
      rgTreeDataHasTop: [],
      roleTreeData: [],
      expandedKeys: [],
      defaultProps: {
        id: 'id',
        label: 'text',
        children: 'children',
        isLeaf: 'isLeaf'
      },
      filterText: '',

      // id存储用户点击的左侧树用户组节点的id
      id: '',
      name: '',
      pid: '',
      queryData: {
        name: ''
      },
      rolesearchData: {},
      tableEmptyText: this.GLOBAL.QUERY.LOADING_TEXT,
      paginationShow: true,
      total: 0,
      roleTableData: null,
      selectedIds: [],
      entity: {},
      // 授予角色模态框
      addRoleConfig: {
        iconConfig: {
          parentType: {
            key: 'rgroup',
            icon: 'vc-icon  vc-icon-tree-rGroup'
          },
          childrenType: {
            key: 'role',
            icon: 'vc-icon vc-icon-tree-role'
          }
        },
        rightKey: 'name',
        editVisible: false,
        title: '操作角色',
        listStyle: 'tree',
        search: {
          title: '请输入',
          patch: 'getRoleByUserName',
          key: 'name',
          params: {}
        },
        defaultProps: {
          id: 'id',
          label: 'name',
          children: 'children',
          isLeaf: 'isLeaf'
        },
        tabTitle: '角色管理',
        allNode: [],
        checked: []
      },
      // 维护用户组模态框
      optionUgroupConfig: {
        iconConfig: {
          parentType: {
            key: 'ugroup',
            icon: 'vc-icon  vc-icon-tree-uGroup'
          },
          childrenType: {
            key: 'ugroup',
            icon: 'vc-icon vc-icon-tree-uGroup'
          }
        },
        rightKey: 'name',
        editVisible: false,
        title: '维护用户组',
        listStyle: 'tree',
        search: {
          title: '请输入',
          patch: 'getUgroupByName',
          key: 'name',
          params: {}
        },
        defaultProps: {
          id: 'id',
          label: 'name',
          children: 'children',
          isLeaf: 'isLeaf'
        },
        tabTitle: '角色管理',
        allNode: [],
        checked: []
      }
    }
  },
  computed: {},
  watch: {
    'tabConfig.activeName': {
      handler (newName, oldName) {
        this.pageConfig.pageNum = 1
        this.getTableData()
      }
    },
    filterText(val) {
      this.$refs.rgTree.filter(this.GLOBAL.filter.filterSpace(val));
    }
  },
  mounted () {
    document.addEventListener(
      'click',
      () => {
        this.menuVisible = false
      },
      false
    )
    this.ini()
  },

  methods: {
    /**
     * 删除用户组用户关联
     */
    deleteUgroup () {
      this.$api
        .deleteUgroup({
          data: {
            ugroupIds: this.selectedIds,
            userId: this.id
          }
        })
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.getTableData()
          } else {
            this.getTableData()
          }
        })
    },
    /**
     * 删除角色用户管理
     */
    deleteRole () {
      this.$api
        .removeUserInRole({
          data: {
            roleIds: this.selectedIds,
            userId: this.id
          }
        })
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.getTableData()
          } else {
            this.getTableData()
          }
        })
    },

    /**
     * 保存用户组
     */
    optionUgroupSave (add, deletelist) {
      this.$api
        .optionUgroup({
          data: {
            userId: this.id,
            addUgroupIds: add,
            removeUgroupIds: deletelist
          }
        })
        .then(res => {
          if (res.success) {
            this.$notifyBox('维护用户组成功', 'success')
            this.pageConfig.pageNum = 1
            this.getTableData(this.id)
          }
          this.optionUgroupConfig.editVisible = false
        })
    },
    /**
     * 操作用户组
     */
    optionUgroup () {
      this.$api.getAllUsergroup_api().then(res => {
        if (!res.success) {
          return
        }
        this.optionUgroupConfig.allNode = res.data
        this.$api
          .getUgroupsByUserId({
            data: {
              userId: this.id
            }
          })
          .then(call => {
            if (call.data) {
              this.optionUgroupConfig.checked = call.data
            } else {
              this.optionUgroupConfig.checked = []
            }
            this.optionUgroupConfig.editVisible = true
          })
      })
    },
    /* 获取表格 */
    getTableData () {
      switch (this.tabConfig.activeName) {
        case 'ugroup':
          this.getUgroupsByUserId()
          break
        case 'role':
          this.getRolesByUserIdPage()
      }
    },
    /**
     * 通过userId查uGroup
     */
    getUgroupsByUserId (
      id = this.id,
      pageNum = this.pageConfig.pageNum,
      pageSize = 15
    ) {
      let item = this.tabConfig.items.filter(i => i.name === 'ugroup')[0]
      this.$api
        .getUgroupsByUserIdPage({
          data: {
            userId: id,
            pageNum: pageNum,
            pageSize: pageSize
          }
        })
        .then(res => {
          if (res.success) {
            if (res.data.records.length !== 0) {
              item.tableConfig.tableData = res.data.records
              this.pageConfig.total = res.data.total
              this.pageConfig.pageNum = res.data.current
            } else if (this.pageConfig.pageNum > 1) {
              this.pageConfig.pageNum--
              this.getTableData()
            } else {
              this.pageConfig.pageNum = 1
              item.tableConfig.tableData = []
            }
          }
        })
    },
    /*
      获取tables
    */
    getRolesByUserIdPage () {
      let item = this.tabConfig.items.filter(i => i.name === 'role')[0]
      this.$api
        .getRolesByUserIdPage({
          data: {
            userId: this.id,
            pageNum: this.pageConfig.pageNum,
            pageSize: 15
          }
        })
        .then(res => {
          if (res.success) {
            if (res.data.records.length !== 0) {
              item.tableConfig.tableData = res.data.records
              this.pageConfig.total = res.data.total
              this.pageConfig.pageNum = res.data.current
            } else if (this.pageConfig.pageNum > 1) {
              this.pageConfig.pageNum--
              this.getTableData()
            } else {
              this.pageConfig.pageNum = 1
              item.tableConfig.tableData = []
            }
          }
        })
    },
    /**
     * saveAdd
     */
    saveAdd (add, deletelist) {
      this.$api
        .removeAndAddRole({
          data: {
            userId: this.id,
            addRoleIds: add,
            removeRoleIds: deletelist
          }
        })
        .then(res => {
          if (res.success) {
            this.$notifyBox('操作角色成功', 'success')
            this.pageConfig.pageNum = 1
            this.addRoleConfig.editVisible = false
            this.getTableData(this.id)
            return
          }
          this.$refs.selectBox.closeDisabled();
        }).catch(err => {
          this.$refs.selectBox.closeDisabled();
        })
    },
    /** 授予角色 */
    addrole () {
      this.getAllroles({
        // 初始化role数据，获取根节点下数据
        data: {
          descendant: '1' // 1代表递归的查询所有孩子
        }
      })
    },
    /**
     * 获取selectBox角色树数据
     */
    getAllroles (p) {
      this.$api.getCurrRole(p).then(res => {
        if (res.success) {
          res.data.forEach(i => {
            i.name = i.data.name
          })
          this.addRoleConfig.allNode = res.data
        }
        this.$api
          .getRolesByUserId({
            data: {
              userId: this.id
            }
          })
          .then(res => {
            if (res.data) {
              this.addRoleConfig.checked = res.data
            } else {
              this.addRoleConfig.checked = []
            }
            this.addRoleConfig.editVisible = true
          })
      })
    },
    refresh () {
      this.reset()
    },
    /**
     * '用户组操作'弹出框关闭事件
     */
    closeOptionUgroupDialog (val) {
      this.optionUgroupConfig.editVisible = false
      this.searchData = {}
      this.pageConfig.pageNum = 1
      this.refresh()
    },
    /**
     * '角色'弹出框关闭事件
     */
    closeAddRoleDialog (val) {
      this.addRoleConfig.editVisible = false
      this.searchData = {}
      this.pageConfig.pageNum = 1
      this.refresh()
    },
    /**
     * 设置是否内置数据的value。数据库只存是 否。但是前台有第三个选项全部。使用""空字符串作查询条件参数代表全部。服务器遇到空字符串作参数才会返回全部信息。
     */
    setInnerValue (val) {
      if (val.code === 2) {
        return ''
      } else {
        return val.code
      }
    },

    ini () {
      this.getAllRole()
    },

    /**
     * 用户组树节点被点击时的回调
     */
    rghandleNodeClick (data) {
      if (data.type === 'user') {
        this.$nextTick(() => {
          this.$refs.rgTree.setCurrentKey(data.id)
          this.reset()
          this.getRightText(data.data)
        })
      } else {
        this.$nextTick(() => {
          this.$refs.rgTree.setCurrentKey(this.id)
        })
      }
    },
    /**
     * 点击页数
     */
    handleCurrentChange (val) {
      this.pageConfig.pageNum = val
      this.getTableData(this.id)
    },

    /**
     * 重置查询条件
     */
    reset () {
      this.queryData = this.GLOBAL.object.clearValOfObj(this.queryData)
    },

    /**
     * 复选框勾选记录勾选的值
     */
    handleSelectionChange (val) {
      this.selectedIds = this.GLOBAL.array.selectOneKey(val, 'id')
    },

    /*
      获取右侧数据 先获取文本框数据
    */
    getRightText (data) {
      this.id = data.id
      this.getTableData(data.id)
    },

    /**
     * 获取左侧角色组树数据,用于各种操作完成后刷新页面。参数用于记住原先的树节点id.
     */
    getAllRole (checkedKey, isGroup = false) {
      this.$api.getTreeData().then(res => {
        if (!res.success) {
          return
        }
        this.treeEmptyText = this.GLOBAL.QUERY.EMPTY_TEXT;
        res.data[0] = res.data[0] || [];
        res.data[1] = res.data[1] || [];
        var temp1 = res.data[0].concat(res.data[1])
        res.data[1].forEach(i => {
          if (!i.pid && i.type === 'user') {
            i.pid = 'other'
          }
        })
        temp1.push({
          id: 'other',
          text: '其他',
          children: [],
          type: 'otherGoup',
          pid: null
        })
        for (var i = temp1.length - 1; i >= 0; i--) {
          // 添加图标
          if (temp1[i].type === 'user') {
            temp1[i].icon = 'vc-icon vc-icon-tree-user'
          } else {
            temp1[i].icon = 'vc-icon vc-icon-tree-org'
          }
        }
        this.rgTreeDataHasTop = this.GLOBAL.array.transToTreeData(temp1)

        this.rgTreeData = this.rgTreeDataHasTop
        if (!checkedKey) {
          this.expandedKeys = []
          let expandedKeys = []
          this.getFirst(this.rgTreeData, expandedKeys)
          if (expandedKeys.length !== 0) {
            this.expandedKeys.push(expandedKeys[0].id)
            this.curkey = expandedKeys[0].id
            this.rghandleNodeClick(expandedKeys[0])
          }
          this.id = expandedKeys[0].id
        }
        if (checkedKey && isGroup === true) {
          // this.expandedKeys.push(checkedKey)
          this.$nextTick(() => {
            this.$refs.rgTree.setCurrentKey(this.curkey)
          })
          this.reset()
        }

        if (!isGroup && checkedKey) {
          let checkedNode = temp1.filter(i => i.id === checkedKey)
          this.expandedKeys = [checkedNode[0].id]
          this.curkey = this.expandedKeys[0]
          this.id = this.expandedKeys[0]
          this.rghandleNodeClick(checkedNode[0])
        }
      })
    },
    /*
      递归找第一个 type = 'permission'
    */
    getFirst (data, expandedKeys) {
      for (const i in data) {
        if (data[i]) {
          let node = data[i]
          if (node.type === 'user') {
            expandedKeys.push(node)
            return
          } else if (node.children && node.children.length !== 0) {
            this.getFirst(node.children, expandedKeys)
          }
        }
      }
    },
    /*
      左侧树图标
    */
    renderContent (h, { node, data, store }) {
      return (
        <span>
          <i class={data.icon}></i>
          <span> {node.label}</span>
        </span>
      )
    },
    /**
     * 对树节点进行筛选
     */
    filterNode(value, data) {
      if (!value) return true;
      return data.text.indexOf(value) !== -1;
    }
  }
}
</script>

<style lang="less">
.keyClass {
  display: flex;
  align-items: center;
  height: 40px;
  justify-content: flex-end;
  color: #999999;
  font-size: 15px;
}
.valueClass {
  display: flex;
  align-items: center;
  height: 40px;
  justify-content: flex-start;
  font-size: 15px;
}
.row-box {
  width: 50%;
  float: left;
  .titleClass {
    display: flex;
    align-items: center;
    background-color: #ebeef5;
    height: 26px;
  }
}

.iconClass {
  width: 5px;
  height: 15px;
  background-color: #2ab099;
  margin-right: 5px;
}
</style>
